package com.wwwarehouse.taskcenter.fragment.warehouse_reg;

import android.os.Bundle;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.filter.SeriesBean;
import com.wwwarehouse.common.eventbus_event.DrawerSeriesCompleteEvent;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.fragment.DeskDrawerSeriesFragment;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.BillBean;
import com.wwwarehouse.taskcenter.bean.OwnerByBuBean;
import com.wwwarehouse.taskcenter.bean.StorageBillBean;
import com.wwwarehouse.taskcenter.bean.StorageBillItemFilterBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * Created by clannad.shao on 2017/11/20.
 *
 * @author clannad_sk
 * @date 2017/11/20
 */
@Route(path = TaskCenterConstant.storageBill)
public class StorageBillFragment extends CommonBasePagerFragment implements DeskDrawerSeriesFragment.OnDeskDrawerItemClickListener{

    private static final int GET_STORAGEBILL_START_PAGE = 1;
    private static final int GET_STORAGEBILL_PAGESIZE = 5;
    private static final int GET_STORAGEBILL_REQUEST_CODE = 0x44;
    private static final int GET_STORAGEBILL_UNIT_REQUEST_CODE = 0x45;
    private static final int GET_STORAGEBILL_GETOWN_BYBU_CODE = 0x46;


    private static final String ITEM_BUSINESS_UNIT = "业务单位";
    private static final String ITEM_OWNER = "货主";
    private static final String ITEM_BILL = "入库单";
    /**
     * 侧边栏初始化数据
     */
    private List<SeriesBean> mFilterList;
    /**
     * 搜索关键词
     */
    private String searchText;
    /**
     * 入库单入参map
     */
    private Map<String, Object> reqParamMap;
    /**
     * 根据业务单位获取货主入参map
     */
    private Map<String, Object> getOwnByBuMap;
    /**
     * 业务单位collection
     */
    private ArrayList<String> businessIdList;
    /**
     * 货主collection
     */
    private ArrayList<String> ownerList;
    /**
     * 入库单状态collection
     */
    private ArrayList<String> statusList;
    /**
     * 货主bean
     */
    private List<FilterBean> filterBean2;
    /**
     * 入库单状态bean
     */
    private List<FilterBean> filterBean3;
    /**
     * 侧边栏实例
     */
    private DeskDrawerSeriesFragment deskDrawerSeriesFragment;

    @Override
    public void requestDatas() {
        super.requestDatas();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        hideConfirmButton();
        ((BaseCardDeskActivity)mActivity).hideSortBt();
        Bundle bundle = getArguments();
        mFilterList = new ArrayList<>();
        setFilterBean();
        if (bundle != null) {
            //这里获取业务单位code  businessIdList
        }
        //获取入库单状态列表
        Map<String, Object> getUnitMap = new HashMap<>();
        getUnitMap.put("codeType", "STORAGE_STATUS");
        loadData(TaskCenterConstant.GET_UNIT, getUnitMap, GET_STORAGEBILL_UNIT_REQUEST_CODE);

        businessIdList = new ArrayList<>();
        businessIdList.add("10001959");
        businessIdList.add("10001507");

        getOwnByBuCode("10001959");
        requestHttp(GET_STORAGEBILL_START_PAGE, GET_STORAGEBILL_PAGESIZE, businessIdList, ownerList, statusList);
    }

    public void getOwnByBuCode(String buId){
        if(getOwnByBuMap == null){
            getOwnByBuMap = new HashMap<>(3 * 2);
        }
        getOwnByBuMap.put("pageNo", GET_STORAGEBILL_START_PAGE);
        getOwnByBuMap.put("buId", buId);
        getOwnByBuMap.put("pageSize", 999);
        loadData(TaskCenterConstant.GET_OWNERID_BY_BUID, getOwnByBuMap, GET_STORAGEBILL_GETOWN_BYBU_CODE);
    }

    public void requestHttp(int pageNo, int pageSize,
                            List<String> businessIdList, List<String> ownerList, List<String> statusList) {
        if (reqParamMap == null) {
            reqParamMap = new HashMap<>();
        }
        reqParamMap.put("pageNo", pageNo);
        reqParamMap.put("pageSize", pageSize);
        reqParamMap.put("searchValue", searchText);
        reqParamMap.put("businessIdList", (businessIdList == null || businessIdList.isEmpty()) ? null : businessIdList);
        reqParamMap.put("ownerList", (ownerList == null || ownerList.isEmpty()) ? null : ownerList);
        reqParamMap.put("statusList", (statusList == null || statusList.isEmpty()) ? null : statusList);
        loadData(TaskCenterConstant.GET_STORAGE_BILL_LIST, reqParamMap, GET_STORAGEBILL_REQUEST_CODE);
    }

    /**
     * 请求成功回调
     *
     * @param data
     * @param what
     */
    @Override
    public void onLoadSuccess(String data, int what) {
        if (what == GET_STORAGEBILL_REQUEST_CODE) {
            StorageBillBean storageBillBean = parseObject(data, StorageBillBean.class);
            //判断异常情况
            if (storageBillBean == null) {
                mStateLayout.showEmptyView(true);
                return;
            }
            if (storageBillBean.getList() == null || storageBillBean.getList().isEmpty()) {
                showEmptyView(R.drawable.contract_no_datalist, R.string.warehouse_reg_storage_bill_no_datalist, false, true);
                return;
            }
            Bundle bundle = new Bundle();
            try {
                //需要传递过滤条件
                bundle.putString("searchText", searchText);
                bundle.putSerializable("businessIdList", businessIdList);
                bundle.putSerializable("ownerList", ownerList);
                bundle.putSerializable("statusList", statusList);
                setData(storageBillBean.getTotal(), GET_STORAGEBILL_PAGESIZE, StorageBillItemFragment.class.getName()
                        , bundle, storageBillBean.getList());
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showToast("数据源为空");
            }
        } else if (what == GET_STORAGEBILL_UNIT_REQUEST_CODE) {
            //获取入库单状态
            //成功
            List<BillBean> billBeanList = JSONObject.parseArray(data, BillBean.class);
            if (billBeanList == null || billBeanList.isEmpty()) {
                return;
            }
            for (BillBean billBean : billBeanList) {
                filterBean3.add(new FilterBean(false, billBean.getName(), billBean));
            }
            notifyDeskDrawerFragment(2);
        } else if (what == GET_STORAGEBILL_GETOWN_BYBU_CODE) {
            //根据业务单位获取货主
            OwnerByBuBean ownerByBuBean = JSONObject.parseObject(data, OwnerByBuBean.class);
            if (ownerByBuBean == null || ownerByBuBean.getList() == null || ownerByBuBean.getList().isEmpty()) {
                return;
            }
            for(OwnerByBuBean.BusinessItem businessItem : ownerByBuBean.getList()){
                filterBean2.add(new FilterBean(false, businessItem.getBusinessUnitName(), businessItem));
            }
            notifyDeskDrawerFragment(1);
        } else {
            //default

        }
    }

    /**
     * requestError
     *
     * @param errorInfo
     */
    @Override
    public void onLoadError(String errorInfo) {
        //异常情况收集处理 TODO
        System.out.println(errorInfo);
    }

    /**
     * 侧边栏点击业务单位关联货主
     * @param pos
     * @param view
     * @param isSelected
     * @param title
     */
    @Override
    public void onDeskItemClick(int pos, View view, boolean isSelected, String title) {
        if(ITEM_BUSINESS_UNIT.equals(title)){
            //只有业务单位点击才需要请求  根据业务单位获取货主
            getOwnByBuCode("10001959");
        }
    }

    /**
     * 点击完成回调  过滤条件
     * @param event
     */
    public void onEventMainThread(DrawerSeriesCompleteEvent event) {
        //点击完成
        if(event == null || event.getList() == null || event.getList().isEmpty()){
            return;
        }
        List<SeriesBean> seriesBeanList = event.getList();
        for(SeriesBean seriesBean : seriesBeanList){
            if(StringUtils.isNullString(seriesBean.getTitle())){
                continue;
            }
            ArrayList<String> paramList = new ArrayList<>();
            for(FilterBean filterBean : seriesBean.getList()){
                if(!filterBean.isSelect()){
                    continue;
                }
                if(ITEM_BUSINESS_UNIT.equals(seriesBean.getTitle())){
                    //业务单位
                    paramList.add(((StorageBillItemFilterBean)filterBean.getData()).getCode());
                }else if(ITEM_OWNER.equals(seriesBean.getTitle())){
                    paramList.add(((OwnerByBuBean.BusinessItem)filterBean.getData()).getBusinessUnitId());
                }else if(ITEM_BILL.equals(seriesBean.getTitle())){
                    paramList.add(((BillBean)filterBean.getData()).getCode());
                }
            }
            if(ITEM_BUSINESS_UNIT.equals(seriesBean.getTitle())){
                if(businessIdList != null && !businessIdList.isEmpty()){
                    businessIdList.clear();
                }
                businessIdList = paramList;
            }else if(ITEM_OWNER.equals(seriesBean.getTitle())){
                if(ownerList != null && !ownerList.isEmpty()){
                    ownerList.clear();
                }
                ownerList = paramList;
            }else if(ITEM_BILL.equals(seriesBean.getTitle())){
                if(statusList != null && !statusList.isEmpty()){
                    statusList.clear();
                }
                statusList = paramList;
            }
        }
        requestHttp(GET_STORAGEBILL_START_PAGE, GET_STORAGEBILL_PAGESIZE, businessIdList, ownerList, statusList);
    }

    /**
     * 初始化侧边栏
     */
    private void setFilterBean() {
        List<FilterBean> filterBean1 = new ArrayList<>();
        filterBean1.add(new FilterBean(false, "杭州网仓科技有限公司", new StorageBillItemFilterBean("杭州网仓科技有限公司", "12837")));
        filterBean1.add(new FilterBean(false, "一个", new StorageBillItemFilterBean("一个", "123412")));

        mFilterList.add(new SeriesBean(ITEM_BUSINESS_UNIT, filterBean1, 1, true));
        filterBean2 = new ArrayList<>();
        mFilterList.add(new SeriesBean(ITEM_OWNER, filterBean2, 1, false));
        filterBean3 = new ArrayList<>();
        mFilterList.add(new SeriesBean(ITEM_BILL, filterBean3, 3, false));

        deskDrawerSeriesFragment = DeskDrawerSeriesFragment.newInstance(mFilterList);
        deskDrawerSeriesFragment.setOnDeskDrawerItemClickListener(this);
        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerSeriesFragment);
    }


    /**
     * 側邊欄
     */
    @Override
    public void filterClick() {
        super.filterClick();
        if (peekFragment() instanceof StorageBillFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    /**
     * 模糊搜索
     * @param text
     */
    @Override
    public void searchNoRealTimeClick(String text) {
        super.searchNoRealTimeClick(text);
        searchText = text;
        requestHttp(GET_STORAGEBILL_START_PAGE, GET_STORAGEBILL_PAGESIZE, businessIdList, ownerList, statusList);
    }

    /**
     * stateLayout click to refresh
     */
    @Override
    public void onRefreshListener() {
        requestHttp(GET_STORAGEBILL_START_PAGE, GET_STORAGEBILL_PAGESIZE, businessIdList, ownerList, statusList);
    }

    /**
     * navigation 设置标题
     */
    @Override
    public void setTitle() {
        if (peekFragment() instanceof StorageBillFragment) {
            mActivity.setTitle(getString(R.string.warehouse_reg_title));
        }
    }

    /**
     * 刷新侧边栏
     * @param pos
     */
    private void notifyDeskDrawerFragment(int pos){
        if (deskDrawerSeriesFragment != null) {
            deskDrawerSeriesFragment.notifyDataChanged(pos);
        }
    }


    /**
     * destory
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
